#coding:utf-8
from util import rt,rp
import os
os.sys.path.insert(0,os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
from django.http import HttpResponseRedirect,HttpResponse
from model import *
from model import invest as invest_modul
import lesscpy
from six import StringIO
import math,json
from django.db.models import Sum
from django.db import connection
from decimal import Decimal
import time,datetime
import hashlib
from calendar import monthrange
from Crypto.Cipher import DES
import base64
import urllib2,json
from util import rp,login_user,pay_url,rt
import urllib
BS = DES.block_size
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS) 
unpad = lambda s : s[0:-ord(s[-1])]
KEY = "81b******" # 'client_secret':'81b' 前八位key和iv ，希财规定 
_HTTP_GET = 'GET'
_HTTP_POST = 'POST'
_HTTP_UPLOAD = 'UPLOAD' 
class DESCipher:
    def __init__( self, key ):
        """
        Requires hex encoded param as a key
        """
        self.key = key

    def encrypt( self, raw ):
        """
        Returns hex encoded encrypted value!
        """
        raw = pad(raw)
        iv = self.key;
        cipher = DES.new( self.key, DES.MODE_CBC, iv )
        return cipher.encrypt( raw ) 

    def decrypt( self, enc ):
        """
        Requires hex encoded param to decrypt
        """
        iv = self.key;
        cipher = DES.new(self.key, DES.MODE_CBC, iv )
        return cipher.decrypt( enc)
        
class JsonDict(dict):
    def __getattr__(self, attr):
        try:
            return self[attr]
        except KeyError:
            raise AttributeError(r"'JsonDict' object has no attribute '%s'" % attr)

    def __setattr__(self, attr, value):
        self[attr] = value


def csai_login(rq):
    '''
        希财账户通
    ''' 
    sign = rq.GET.get('sign')
    print sign
    print '***********'
    reurl = rq.META.get('HTTP_REFERER')
    # 对网页源做校验，如果不是cscai传过来的，直接return
    # if reurl.find('csai.cn') == -1:
        # return rp(u'wrong request url')  
    if sign=='':
        return rp(u'sign is not none ')
    sign=sign.replace(' ','+')
    data=base64.b64decode(sign)    
    decryptor = DESCipher(KEY)
    plaintext = decryptor.decrypt(data)
    print plaintext
    data = {
        "result": sign,
    }

    list_sign = (plaintext.split('&'))[:3]
    phone= list_sign[0].split('=')[1:2][0]
    name= list_sign[1].split('=')[1:2][0]
    pid= int(list_sign[2].split('=')[1:2][0].replace('\x06',''))
    u = user.objects.filter(phone=phone)[:1]
    print u.query
    if u:
        u = u[0]
        if u and u.status == 'unvalid':
            return rp('wrong user')
        else:
           return _csaipost(phone,name,pid) #如果手机号存在，刚post回希财
    else:
        #保存用户手机号，生成一个带cscai_前缀的name
        u = user()
        u.phone = phone
        u.nickname='csai_'+name
        u.password = hashlib.md5(phone).hexdigest().lower()
        u.status = 'valid'
        u.phone_status = 'pass'        
        u.create_at = datetime.datetime.now()
        u.save()
        cps(type='register',user_id=u.id,code='csai',create_at=datetime.datetime.now()).save()
        login_user(rq,u.id)
        return HttpResponseRedirect('/index/index')
       
def _csaipost(phone,name,pid):
    ac=_get_access_token()
    sign='phone='+phone+'&name='+name+'&result=1'
    encryptor = DESCipher(KEY)
    plaintext1 = base64.b64encode(encryptor.encrypt(sign))

    
    resp_text = _http('POST', 'http://api.csai.cn/api/BindUserCallBack', \
    sign=plaintext1,access_token=ac)
    return HttpResponseRedirect('/index/index')
    
def _investcsaipost():
    '''
        投资回调
    '''
    ac=_get_access_token()
    post_at = (datetime.datetime.now()).strftime("%Y-%m-%d")
    end_at = (datetime.datetime.now() + datetime.timedelta(days = 1)).strftime("%Y-%m-%d")
    ps = project.objects.filter(full_at__gte=post_at,full_at__lt=end_at)

    if len(ps):
        for p in ps:
            invest_res=invest_modul.objects.filter(project_id=p.id)
            for iv in invest_res:
                cps_res=cps.objects.filter(user_id=iv.user_id,code='csai')[:1]
                print cps_res.query
                if len(cps_res):
                    user_res=user.objects.get(pk=cps_res[0].user_id)
                    number=iv.number
                    phone=user_res.phone
                    dt=p.full_at.strftime("%Y-%m-%d")
                    url="https://www.dangpoo.com/project/%s" %(p.id)
                    pid=p.id
                    commision=0
                    investamount=iv.money
                    sign="id=%s&phone=%s&Datetime=%s&COMmision=%s&pid=%d&url=%s&InvestAmount=%s&Earnings=0" %(number,phone,dt,commision,pid,url,investamount)
                    print sign
                    encryptor = DESCipher(KEY)
                    plaintext1 = base64.b64encode(encryptor.encrypt(sign)) \
                    
                    resp_text = _http('POST', 'http://api.csai.cn/api/InvestCallBack', \
                    sign=plaintext1,access_token=ac)
                    print plaintext1

def _http(method, url, headers=None, **kw):
    '''
    Send http request and return response text.
    '''
    params = None
    boundary = None
    if method=='UPLOAD':
        params, boundary = _encode_multipart(**kw)
    else:
        params = _encode_params(**kw)
    http_url = '%s?%s' % (url, params) if method==_HTTP_GET else url
    http_body = None if method=='GET' else params
    req = urllib2.Request(http_url, data=http_body)
    req.add_header('Accept-Encoding', 'gzip')
    if headers:
        for k, v in headers.iteritems():
            req.add_header(k, v)
    if boundary:
        req.add_header('Content-Type', 'multipart/form-data; boundary=%s' % boundary)
    try:
        resp = urllib2.urlopen(req, timeout=5)
        return _read_http_body(resp)
    finally:
        pass

def _read_http_body(http_obj):
    using_gzip = http_obj.headers.get('Content-Encoding', '')=='gzip'
    body = http_obj.read()
    if using_gzip:
        gzipper = gzip.GzipFile(fileobj=StringIO(body))
        fcontent = gzipper.read()
        gzipper.close()
        return fcontent
    return body



def _parse_json(s):
    return json.loads(s, object_hook=lambda pairs: JsonDict(pairs.iteritems()))

def _encode_params(**kw):
    
    def _encode(L, k, v):
        if isinstance(v, unicode):
            L.append('%s=%s' % (k, urllib.quote(v.encode('utf-8'))))
        elif isinstance(v, str):
            L.append('%s=%s' % (k, urllib.quote(v)))
        elif isinstance(v, collections.Iterable):
            for x in v:
                _encode(L, k, x)
        else:
            L.append('%s=%s' % (k, urllib.quote(str(v))))
    args = []
    for k, v in kw.iteritems():
        _encode(args, k, v)
    return '&'.join(args)
    
def _get_access_token():
    resp_text = _http('POST', 'http://api.csai.cn/oauth2/access_token2', \
    client_id='1340e58f4',client_secret='81b78c0824')
    ac = _parse_json(resp_text)
    return ac.access_token
    
            
    